<?php

namespace App\Http\Controllers\Account;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Components\SmsComponent;
use App\Http\Components\UserComponent;

use DB;
use App\Models\UserModel;

use App\library\UtilFunction;

/**
 * 发送短信接口
 */
class PayCheckCodeController extends AccountController{

    public function __construct(){
        parent::__construct();        
    }

    /*版本控制，对应app版本跳转对应接口*/
    public function version_invoke(Request $request){
        $appversion = $request->input('appversion');
        $apptype = $request->input('apptype');
        if ($appversion && $apptype) {
            return $this->pay_check_code($request);
        }else{
            return $this->json('102','该app版本下无此接口，请更新app');
        }
    }

    /*获取短信验证码*/
    public function pay_check_code(Request $request){
        $user = UserComponent::check_token($request);
        $user_id = $user['user_id'];

        $customAttr = [
            'pay_password' => '支付密码',
            'pay_password_confirm' => '支付密码确认',
        ];
        /*暂时不做校验*/
        $this->validate($request, [
            'pay_password' => 'required|digits:6',
            'pay_password_confirm' => 'required|digits:6|same:pay_password',
        ],[ ], $customAttr);

        $user = UserModel::where('user_id',$user_id)->first();
        $phone = $user->phone;
        $code_type = 'pay_password';

        $sms = new SmsComponent();
        $sms_return = $sms->send_check_code($phone,$code_type);
        
        if($sms_return){
            if (is_array($sms_return)) {
                if (isset($sms_return['error_code'])) {
                    return $this->json('0','发送失败：['.$sms_return['error_code'].']'.$sms_return['reason']);
                }elseif (isset($sms_return['count']) && isset($sms_return['time'])) {
                    $count = $sms_return['count'];
                    $time = UtilFunction::word_time($sms_return['time']);
                    return $this->json('0',"发送过于频繁,在{$time}内只能发送 {$count} 条短信");
                }else{
                    return $this->json('0','发送短信验证码失败');
                }
            }elseif (intval($sms_return)) {
                $data['phone'] = $phone;
                return $this->json('1','短信发送成功'.$sms_return,$data);
            }else{
                return $this->json('0','短信发送失败');
            }
        }else{
            return $this->json('0','发送失败');
        }
    }
}
